package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.MdmEnclosureFileDownDto;
import com.kaili.basic.pojo.dto.MdmOrgQueryDto;
import com.kaili.basic.pojo.dto.MdmOpinionAddDto;
import com.kaili.basic.pojo.dto.MdmOpinionQueryDto;
import com.kaili.basic.pojo.entity.*;
import com.kaili.basic.service.IMdmOpinionService;
import com.kaili.basic.service.IMdmOrgService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.aop.OperateLogAspect;
import com.kaili.common.aop.log.enums.FunctionName;
import com.kaili.common.aop.log.enums.OperateType;
import com.kaili.common.exception.RestException;
import com.kaili.common.fastdfs.FastDFSClient;
import com.kaili.common.fastdfs.UploadController;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.MailUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 意见建议控制类
 * Created by linjian on 19-7-31.
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "意见建议", description = "意见建议相关API")
@RestController
public class MdmOpinionController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IMdmOpinionService IMdmOpinionService;

    @Autowired
    private IMdmOrgService mdmOrgService;


    /**
     * @Desc:  条件查询mdm消息
     * @author: TBS
     * @Time: 2019/8/9 11:24
     * @param mdmOrgQueryDto
     * @return java.util.List<com.kaili.basic.pojo.entity.MdmOrgEntity>
     */
    @ResponseBody
    @GetMapping(value = "/opinions/searchRanges")
    @ApiOperation(value = "模糊查询机构",notes = "模糊查询机构")
    public List<MdmOrgEntity> queryMdmMessages(@ModelAttribute MdmOrgQueryDto mdmOrgQueryDto) {
        return mdmOrgService.queryOrgRanges(mdmOrgQueryDto);
    }

    /**
     * 查看意见
     */
    @GetMapping("/opinions/query/{userId}")
    @ApiOperation(value = "查看意见", notes = "查看意见")
    public MdmOpinionResultEntity viewOpinion(@ApiParam("userId") @PathVariable("userId") Integer id){

        //根据id获得意见
        MdmOpinionEntity baseOpinion = IMdmOpinionService.queryOpinionById(id);
        //将字符串转为数组
        MdmOpinionResultEntity resultEntity = new MdmOpinionResultEntity();
        resultEntity.setMenuId(baseOpinion.getMenuId());
        resultEntity.setOpinionTitle(baseOpinion.getOpinionTitle());
        resultEntity.setDescription(baseOpinion.getDescription());

        String[] fileName = baseOpinion.getEnclosureName().split(";");
        String[] filePath = baseOpinion.getEnclosurePath().split(";");
        String[] emailAddress = baseOpinion.getEmailAddress().split(";");
        Map<String,String> map = new HashMap<>();
        List<Map<String,String>> list = new ArrayList<>();
        int len = fileName.length > filePath.length ? filePath.length : filePath.length;
        for (int i=0;i<len;i++){
            map.put("fileName",fileName[i]);
            map.put("filePath",filePath[i]);
            list.add(map);
        }
        resultEntity.setEnclosureName(list);
        resultEntity.setEmailAddress(emailAddress);
        if (baseOpinion.getRdStatus()==2){
            //变更状态为已查看
            IMdmOpinionService.updateRdStatusById(id);
        }
        return resultEntity;
    }

    /**
     * 意见查询
     */
    @ApiOperation(value = "分页查询意见信息", notes = "分页查询意见信息")
    @GetMapping("/opinions/query")
    public Page<MdmOpinionInfoEntity> getBaseOpinionByCondition(@ModelAttribute @Validated MdmOpinionQueryDto dto){
        return IMdmOpinionService.getBaseOpinionByCondition(new Page<MdmOpinionInfoEntity>(dto.getPage(), dto.getPageSize()), dto);
    }

    /**
     * 新增意见
     */
    @ApiOperation(value = "新增意见", notes = "新增意见")
    @PostMapping("/opinions/add")
    @OperateLogAspect(functionName = FunctionName.opinion,operateType = OperateType.ADD, key = "opinion")
    public RestStatus addOpinions(MdmOpinionAddDto dto, @RequestParam("file") MultipartFile[] file){
        MdmOpinion opinion = getFormData(dto,file);
        BeanUtils.copyProperties(dto,opinion);

        String emails = opinion.getEmailAddress();
        String[] email = null;
        if (null != emails && !emails.equals("")){
            //获得邮箱数组
           email =  emails.split(";");
           if (email.length>10){
               //输入的邮箱超过10个
               return CommonStatus.ADD_FAIL_MAIL;
           }
           //判断邮箱格式是否正确
           boolean flag =  patternMail(email);
           if (!flag){
               return CommonStatus.ADD_MAIL_ERROR;
           }
        }
        /*Long createdBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        if (createdBy == null){
            opinion.setCreatedBy(-1L);
        }*/
        opinion.setCreatedBy(1L);
        opinion.setCreatedTime(new Date());
        opinion.setProductName("mdm产品");
        IMdmOpinionService.addOpinion(opinion);
        //增加成功后向抄送的邮箱发送邮件
        HashMap mailMap = new HashMap<String,String>();
        mailMap.put("subject",opinion.getOpinionTitle());
        mailMap.put("content",opinion.getDescription());
        mailMap.put("emailAddress",opinion.getEmailAddress());
        //MultipartFile转文件
        List<File> fileUrl = null;
        try {
            fileUrl = multipartFileToList(file);
            int i =  MailUtil.sendEmail(mailMap,fileUrl);
            if (i != 1){
                //邮件发送失败
                return CommonStatus.ADD_EMAIL_DEFAULT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonStatus.ADD_EMAIL_OK;
    }

    //MultipartFile数组转文件
    public List<File> multipartFileToList(MultipartFile[] file) throws Exception {
        List<File> list = new LinkedList<>();
        if (file.length > 6){
            return null;
        }
        for (int i = 0; i < file.length; i++) {
            InputStream ins = file[i].getInputStream();
            File f = new File(file[i].getOriginalFilename());
            OutputStream os = new FileOutputStream(f);
            int byteRead = 0;
            byte[] buffer = new byte[1024];
            while ((byteRead = ins.read(buffer,0,1024)) != -1){
                os.write(buffer,0,byteRead);
            }
            list.add(f);
            os.close();
            ins.close();
        }
        return list;
    }

    private MdmOpinion getFormData(MdmOpinionAddDto dto, MultipartFile[] file) {
        MdmOpinion entity = new MdmOpinion();
        BeanUtils.copyProperties(dto,entity);
        try {
            String filePath = "";
            String fileName = "";
            int j = 0;
            if (null != file && file.length != 0) {
                for (int i = 0; i < file.length;i++){
                    j++;
                    String path = UploadController.saveFile(file[i]);
                    String name = file[i].getOriginalFilename();
                    if (j == file.length){
                        filePath = filePath+path;
                        fileName = fileName+name;
                    }else{
                        filePath = filePath+path+";";
                        fileName = fileName+name+";";
                    }
                }
            }
            entity.setEnclosurePath(filePath);
            entity.setEnclosureName(fileName);
        } catch (IOException e) {
            logger.debug("文件获取异常:"+e);
        }
        return entity;
    }

    //判断邮箱数组是否正确
    public boolean patternMail(String[] arr){
        //邮箱校验规则
        String martch = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        for (int i = 0 ; i < arr.length; i++) {
            if (!arr[i].matches(martch)){
                return false;
            }
        }
        return true;
    }

    /**
     * 数据导出
     */
    @GetMapping("/opinions/export")
    @ApiOperation(value = "导出意见详细信息")
    public void export(HttpServletResponse response, @ModelAttribute MdmOpinionQueryDto dto) throws RestException {
        List<MdmOpinionExport> list = IMdmOpinionService.opinionInfoExport(dto);
        ExcelUtil.exportExcel(list,"意见详细信息","sheet1", MdmOpinionExport.class, UUID.randomUUID().toString()+".xls",response);
    }

    /**
     * 附件下载
     */
    @GetMapping(value = "/opinions/downloadFile")
    @ApiOperation("附件下载")
    public void downloadFile( HttpServletResponse response,@ModelAttribute MdmEnclosureFileDownDto dto) throws Exception {

        String filePath = dto.getEnclosurePath();
        String fileName = dto.getEnclosureName();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("image/png");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test"+fileName, "UTF-8"));
        filePath = filePath.substring(filePath.indexOf("g"));
        byte[] ins = FastDFSClient
                .downImage(filePath.substring(0, filePath.indexOf("/")),
                        filePath.substring(filePath.indexOf("/") + 1));
        response.setContentLength(ins.length);
        OutputStream os = response.getOutputStream();
        os.write(ins);
        os.flush();
        os.close();
    }

    /**
     * 返回一级菜单
     */
    @GetMapping("/opinions/navlist")
    @ApiOperation(value = "查询菜单", notes = "查询菜单")
    public List<MdmBaseMenu> queryPageList(){
        List<MdmBaseMenu> treeList = IMdmOpinionService.getTreeList();
        return treeList;
    }
}
